import { Injectable } from '@nestjs/common'
import { InjectRepository } from '@nestjs/typeorm'
import { formatDate } from 'src/utils'
import { Repository, Not, IsNull } from 'typeorm'
import { Staff } from '../staff/entities/staff.entity'
import { CreateChangeSalaryDto } from './dto/create-change-salary.dto'
import { UpdateChangeSalaryDto } from './dto/update-change-salary.dto'
import { ChangeSalary } from './entities/change-salary.entity'

@Injectable()
export class ChangeSalaryService {
  constructor(
    @InjectRepository(ChangeSalary)
    private readonly chagneSalary: Repository<ChangeSalary>,
    @InjectRepository(Staff)
    private readonly staff: Repository<Staff>
  ) {}
  async create(createChangeSalaryDto: CreateChangeSalaryDto) {
    const changeSalary = new ChangeSalary()
    const staff = await this.staff.findOne({
      where: { id: createChangeSalaryDto.staffId }
    })
    changeSalary.staff = staff
    changeSalary.beforeSalary = createChangeSalaryDto.beforeSalary
    changeSalary.afterSalary = createChangeSalaryDto.afterSalary
    changeSalary.reason = createChangeSalaryDto.reason
    changeSalary.remark = createChangeSalaryDto.remark
    changeSalary.date = formatDate(new Date())
    await this.staff.update(staff.id, {
      basisSalary: createChangeSalaryDto.afterSalary
    })
    return this.chagneSalary.save(changeSalary)
  }
  async findAll(
    params: {
      page: number
      pageSize: number
      isDelete?: boolean
    },
    staffId?: number
  ) {
    const where = {}
    params.isDelete && (where['deleteDate'] = Not(IsNull()))
    staffId && (where['staff'] = { id: staffId })
    const data = await this.chagneSalary.find({
      where: { ...where },
      withDeleted: params.isDelete,
      relations: ['staff'],
      skip: (params.page - 1) * params.pageSize,
      take: params.pageSize,
      order: { id: 'DESC' }
    })
    const total = await this.chagneSalary.count({
      where: { ...where },
      relations: ['staff'],
      withDeleted: params.isDelete
    })
    const newData = data.map(item => {
      return {
        ...item,
        staff: {
          id: item.staff.id,
          name: item.staff.name
        }
      }
    })
    return { data: newData, total }
  }

  update(id: number, updateChangeSalaryDto: UpdateChangeSalaryDto) {
    return this.chagneSalary.update(id, updateChangeSalaryDto)
  }

  remove(ids: number[]) {
    return this.chagneSalary.softDelete(ids)
  }

  restore(ids: number[]) {
    return this.chagneSalary.restore(ids)
  }
}
